package com.atguigu.yygh.sms.service.impl;

import com.atguigu.yygh.sms.service.SmsService;
import com.atguigu.yygh.sms.utils.HttpUtils;
import com.atguigu.yygh.sms.utils.RandomUtil;
import com.atguigu.yygh.vo.msm.MsmVo;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description:这个微服务是完成登录验证码的
 * @author :又菜又爱玩的→速趴塞亚锦←
 * @create :2023/5/18
 * @param  :1.8
 */
@Service
public class SmsServiceImpl  implements SmsService {


    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean sendCode(String phone) {
        String redisCode = (String)redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(redisCode)){
            return true;
        }
        //TODO 这里是重点
        String host = "https://gyytz.market.alicloudapi.com";
        String path = "/sms/smsSend";
        String method = "POST";
        String appcode = "eebdfcd67ce34166bb9c6764dd6b8987";

        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);

        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", phone);

        String fourBitRandom = RandomUtil.getFourBitRandom();//生成随机数
        System.out.println(fourBitRandom);
        querys.put("param", "code:"+fourBitRandom);

        querys.put("tpl_id", "TP1711063");
        Map<String, String> bodys = new HashMap<String, String>();


        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));

            //把验证码保存redis中一份
            redisTemplate.opsForValue().set(phone,fourBitRandom,16, TimeUnit.DAYS);//这里是保存16天意思！！！！

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * @description://阿里云发送短信提示：个人用户、、阿里云用不了了，就在这里模拟一个
     * @author :又菜又爱玩的→速趴塞亚锦←
     * @create :2023/5/21
     * @param  :1.8
     */
    @Override
    public void sendMessage(MsmVo msmVo) {
        String phone = msmVo.getPhone();
        //阿里云发送短信提示：个人用户、、阿里云用不了了，就在这里模拟一个
        //模板 //模板参数
        System.out.println("给就诊人发送短信提示成功");
    }
}
